﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace AnaViewer
{
    partial class ScreenSaverForm : Form
    {
        /// <summary>
        /// 文章更换计时器。
        /// </summary>
        private Timer articleTimer;
        /// <summary>
        /// 屏保变化计时器。该计时器刷新语录位置和背景图片。
        /// </summary>
        private Timer timer;
        /// <summary>
        /// 背景图片变化计时器。Interval = 10*000
        /// </summary>
        //Timer backgroundChangeTimer;

        Properties.Settings settings = Properties.Settings.Default;
        ThemeHelper themeHelper = ThemeHelper.Default;


        //// 用于显示 RSS 内容的对象
        //private ItemListView<RssItem> rssView;
        //private ItemDescriptionView<RssItem> rssDescriptionView;

        // 在背景中显示的图像
        private Image backgroudImage = null;
        private List<string> imageFileNames;
        private int currentImageIndex;

        // 跟踪屏幕保护程序是否已激活。
        private bool isActive = false;

        // 跟踪鼠标的位置
        private Point mouseLocation;

        private List<string> imageExtensions = new List<string>(new string[] { "*.bmp", "*.gif", "*.png", "*.jpg", "*.jpeg" });


        Size anaSize = new Size(500, 200);
        /// <summary>
        /// 语录绘制的位置。
        /// </summary>
        Point AnaLocation = new Point(0, 0);
        /// <summary>
        /// 背景图片绘制的区域。
        /// </summary>
        Rectangle imageRect = Rectangle.Empty;
        /// <summary>
        /// 随机数。
        /// </summary>
        Random random = new Random();
        AnaPainter anaPainter;
        public ScreenSaverForm()
        {
            InitializeComponent();

#if !DEBUG
            this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.ScreenSaverForm_MouseMove);
            this.KeyDown += delegate(object sender, KeyEventArgs e) { Close(); };
            this.MouseDown += delegate(object sender, MouseEventArgs e) { Close(); };
#endif

            SetupScreenSaver();
            LoadBackgroundImage();

            anaSize =settings.ScreenSaver_AnaSize;
            anaPainter = new AnaPainter(this, new Rectangle(0, 0, anaSize.Width, anaSize.Height));

            //第一次居中显示
            AnaLocation = new Point((this.Width - anaSize.Width) / 2, (this.Height - 150) / 2);

            articleTimer = new Timer();
            articleTimer.Interval = settings.ChangeArticleInterval * 1000;
            //articleTimer.Tick += delegate(object sender, EventArgs e) { subject.NextArticle(); };

            timer = new Timer();
            timer.Interval = 10 * 1000;
            timer.Tick += new EventHandler(timer_Tick);

            UseImageBack = settings.ScreenSaver_UseImageBack;

        }



        void timer_Tick(object sender, EventArgs e)
        {//注意，该定时器要求的效果是，即使 Subject 没有数据，语录不切换，语录的显示位置也要改变
            subject.NextArticle();

            // ------------- 语录位置 -------------
            Size size = anaPainter.RealRect.Size;//AnaSize
            int x = random.Next(this.Width - size.Width);
            int y = random.Next(this.Height - size.Height);
            AnaLocation = new Point(x, y);

            if (UseImageBack)
            {
                ChangeBackgroundImage();
                if (backgroudImage != null)
                {
                    // ------------- 背景图片位置 -------------
                    //产生一个随机的位置
                    x = 0; y = 0;
                    if (this.Width < backgroudImage.Width)//居中
                        x = (this.Width - backgroudImage.Width) / 2;
                    else
                        x = random.Next(this.Width - backgroudImage.Width);
                    if (this.Height < backgroudImage.Height)//居中
                        y = (this.Height - backgroudImage.Height) / 2;
                    else
                        y = random.Next(this.Height - backgroudImage.Height);
                    imageRect = new Rectangle(x, y, backgroudImage.Width, backgroudImage.Height);
                }
            }
            this.Invalidate();
        }
        int defaultImageIndex = 0;
        /// <summary>
        /// 改变背景图片。如果图片文件列表为空，则加载默认的图片。
        /// </summary>
        void ChangeBackgroundImage()
        {
            // ------------- 背景图片 -------------
            if (imageFileNames.Count <= 0)
            {//图片文件列表为空，则在两张间切换

                //// 如果出于某种原因无法加载背景图像，
                //// 则使用资源中存储的图像
                //images.Add(Properties.Resources.SSaverBackground);
                //images.Add(Properties.Resources.SSaverBackground2);
                defaultImageIndex = (defaultImageIndex + 1) % 2;
                if (defaultImageIndex == 0)
                    backgroudImage = Properties.Resources.SSaverBackground;
                else
                    backgroudImage = Properties.Resources.SSaverBackground2;
            }
            else
            {
                // 将背景图像更改为下一幅图像。
                currentImageIndex = (currentImageIndex + 1) % imageFileNames.Count;
                // 尝试加载图像
                try
                {
                    string fullPath = imageFileNames[currentImageIndex];
                    backgroudImage = Image.FromFile(fullPath);
                }
                catch (OutOfMemoryException)
                {
                    // 如果图像无法加载，则继续。
                }
                catch (Exception)
                { }
            }
        }

        AnaSubject subject;
        public AnaSubject Subject
        {
            get { return subject; }
            set
            {
                subject = value;
                if (subject != null)
                {
                    subject.SelectedIndexChanged += delegate(object sender, EventArgs e)
                    {
                        anaPainter.DisplayItem = subject.SelectedItem;
                        //anaPainter.IsHover = true;
                    };
                    subject.ItemsListChanged += new EventHandler(source_ItemsListChanged);
                }
            }
        }

        void source_ItemsListChanged(object sender, EventArgs e)
        {
            if (subject.AnaItems.Count > 0)
            {
                if (subject.SelectedIndex < 0 || subject.SelectedIndex >= subject.AnaItems.Count)
                    subject.SelectedIndex = 0;
            }
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            anaPainter.UpdateTheme(themeHelper.GetThemeData(settings.ScreenSaver_AnaTheme));
            //刷新，产生背景图片，使第一次显示的位置也是随机的
            timer_Tick(this, null);
            //articleTimer.Start();
            timer.Start();

        }


        /// <summary>
        /// 将主窗体设置为全屏显示的屏幕保护程序。
        /// </summary>
        private void SetupScreenSaver()
        {
            this.SetStyle(ControlStyles.AllPaintingInWmPaint
                | ControlStyles.OptimizedDoubleBuffer
                | ControlStyles.ResizeRedraw
                | ControlStyles.Selectable
                | ControlStyles.SupportsTransparentBackColor
                | ControlStyles.UserPaint, true);

            // 使用双缓冲来改进绘制性能
            this.SetStyle(ControlStyles.OptimizedDoubleBuffer
                | ControlStyles.UserPaint
                | ControlStyles.AllPaintingInWmPaint, true);
            // 捕获鼠标
            this.Capture = true;

            // 将应用程序设置为全屏模式并隐藏鼠标
            Bounds = Screen.PrimaryScreen.Bounds;
            WindowState = FormWindowState.Maximized;
#if !DEBUG
            ShowInTaskbar = false;
            this.TopMost = true;
            Cursor.Hide();
#endif
            DoubleBuffered = true;
            BackgroundImageLayout = ImageLayout.Stretch;
        }

        private void LoadBackgroundImage()
        {
            // 初始化背景图像。
            imageFileNames = new List<string>();
            currentImageIndex = 0;

            string path = Properties.Settings.Default.BackgroundImagePath;
            if (Directory.Exists(path))
            {// 尝试加载用户指定的图像文件列表。
                // 对于每种图像扩展名(.jpg、.bmp 等)
                foreach (string imageExtension in imageExtensions)
                {
                    // 对于用户提供的目录中的每个文件
                    foreach (string file in Directory.GetFiles(path,imageExtension))
                        imageFileNames.Add(file);
                }
            }

        }

        private void ScreenSaverForm_MouseMove(object sender, MouseEventArgs e)
        {
            // 仅在第一次调用此事件时设置 IsActive 和 MouseLocation。
            if (!isActive)
            {
                mouseLocation = MousePosition;
                isActive = true;
            }
            else
            {
                // 如果在第一次调用后鼠标发生明显的移动，则关闭。
                if ((Math.Abs(MousePosition.X - mouseLocation.X) > 10) ||
                    (Math.Abs(MousePosition.Y - mouseLocation.Y) > 10))
                {
                    Close();
                }
            }
        }
        /// <summary>
        /// 是否绘制背景图片
        /// </summary>
        bool UseImageBack = true;
        protected override void OnPaintBackground(PaintEventArgs e)
        {
            if (UseImageBack)
            {
                //居中绘制
                if (backgroudImage == null)
                    return;

                if (imageRect == Rectangle.Empty)
                {
                    // 绘制当前背景图像并拉伸至全屏
                    e.Graphics.DrawImage(backgroudImage, 0, 0, Size.Width, Size.Height);
                }
                else
                {//在随机位置绘制
                    e.Graphics.DrawImage(backgroudImage, imageRect);
                }
            }
        }
        protected override void OnPaint(PaintEventArgs e)
        {
            //rssView.Paint(e);
            //rssDescriptionView.Paint(e);
            anaPainter.Paint(new PaintEventArgs(e.Graphics,new Rectangle(AnaLocation,anaSize)));
        }
    }
}
